package com.samphanie.auiu.biz_login

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.samphanie.auiu.biz_login.api.accountApiService
import com.samphanie.auiu.biz_login.databinding.ActivityRegistrationBinding
import com.samphanie.auiu.pub_mod.model.RegisterUser
import com.samphanie.auiu.common.ui.component.AuiuBaseActivity
import com.samphanie.auiu.library.restful.AuiuCallback
import com.samphanie.auiu.library.restful.AuiuResponse

@Route(path = "/account/registration")
class RegistrationActivity : AuiuBaseActivity() {

    private lateinit var registrationBinding : ActivityRegistrationBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        registrationBinding = ActivityRegistrationBinding.inflate(layoutInflater)
        setContentView(registrationBinding.root)

        registrationBinding.actionBack.setOnClickListener {
            onBackPressed()
        }

        registrationBinding.actionRegister.setOnClickListener {
            submit()
        }
    }

    private fun submit() {
        val username = registrationBinding.inputItemUsername.getEditText().text.toString()
        val password = registrationBinding.inputItemPassword.getEditText().text.toString()

        if (username.isBlank()) {
            showToast("请输入用户名")
            return
        }
        if (password.isBlank()) {
            showToast("请输入密码")
            return
        }

        accountApiService().register(username, password)
            .enqueue(object : AuiuCallback<RegisterUser> {
                override fun onSuccess(response: AuiuResponse<RegisterUser>) {
                    if (response.code == AuiuResponse.SUCCESS) {
                        // 注册成功
                        val intent = Intent()
                        intent.putExtra("username", username)
                        setResult(Activity.RESULT_OK, intent)
                        finish()
                    } else {
                        showToast(response.message!!)
                    }

                }

                override fun onFailed(throwable: Throwable) {
                    showToast(throwable.message!!)
                }
            })


    }

    private fun showToast(message: String) {
        Toast.makeText(
            applicationContext,
            message,
            Toast.LENGTH_SHORT
        ).show()
    }
}